/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.pucsp.projetoesp.acessoRemoto;

import br.pucsp.projetoesp.EstadoDeJogo;
import br.pucsp.projetoesp.Jogo;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.lang.StringBuilder;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URLDecoder;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

/**
 *
 * @author Ricardo
 */
public class AcessoRemoto implements Runnable {

    ServerSocket serverSocket;
    Jogo jogo;
    private volatile boolean keepRunning;

    public AcessoRemoto(Jogo jogo) throws Exception {
        this.jogo = jogo;
        try {
            serverSocket = new ServerSocket(5837);
            keepRunning = true;
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(null, "Os acessos remotos não podem ser executados enquanto"
                    + " a porta 5837 estiver sendo ocupada");
            throw new Exception();
        }
    }

    @Override
    public void run() {
        while (keepRunning) {
            try {
                Socket alunoConectado = serverSocket.accept();
                processarRequest(alunoConectado);
                alunoConectado.close();
            } catch (IOException ex) {
                Logger.getLogger(AcessoRemoto.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    private void processarRequest(Socket alunoConectado) {
        try {
            //lerEntrada
            InputStream inputStream = alunoConectado.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

            String linha = reader.readLine();
            System.out.println("linha = " + linha);
            while (linha != null) {
                System.out.println("linha = " + linha);
                if (linha.contains("GET / HTTP/1.1")) {
                    retornarHtml0(alunoConectado);
                    break;
                } else if (linha.contains("/?nome=")) {
                    int igualIndex = linha.indexOf("=");
                        int HIndex = linha.indexOf("&");
                        String nome = linha.substring(igualIndex + 1, HIndex);
                        nome = nome.replace("+", " ");
                    if (linha.contains("acao=registrar")) {
                        
                        jogo.registrar(nome);
                        retornarHtml1(alunoConectado,nome);
                    }

                    if(linha.contains("verificarinicio")){
                        if(jogo.getEstadoAtual() != null && jogo.getEstadoAtual().equals(EstadoDeJogo.JOGO_INICIADO)){
                            retornarHtml2(alunoConectado,nome);
                        }
                        else
                            retornarHtml1(alunoConectado,nome);
                    }
                    if(linha.contains("verificarsorteio")){
                        if(jogo.getEstadoAtual() != null && jogo.getEstadoAtual().equals(EstadoDeJogo.SORTEADO))
                        {
                            if (jogo.getJogadorSorteado().equals(nome))
                                retornarHtml3(alunoConectado,nome);
                            else
                                retornarHtml2(alunoConectado,nome);
                        }
                        else
                            retornarHtml2(alunoConectado,nome);
                    }
                    if(linha.contains("dicaEscolhida")){
                        retornarHtml4(alunoConectado, nome);
                        break;
                    }
                    break;
                } else if(linha.contains("/EnviarResposta")) {
                    String resposta = linha.split("resposta=")[1];
                    resposta = resposta.split(" ")[0];
                    retornarHtml5(alunoConectado);
                    jogo.enviarResposta(resposta, 0);
                    break;
                }else{
                     break;
                }
            }

        } catch (IOException ex) {
            Logger.getLogger(AcessoRemoto.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void retornarHtml0(Socket alunoConectado) {
        try {
            System.out.println("Fui retornar html0");
            File html0 = new File("paginasResposta\\html0.xhtml");

            PrintWriter writer = new PrintWriter(alunoConectado.getOutputStream());
            BufferedReader htmlReader = new BufferedReader(new FileReader(html0));
            String htmlEmString = converterHtmlString(htmlReader);
            System.out.println(htmlEmString);
            writer.write(htmlEmString);
            writer.close();

        } catch (IOException ex) {
            Logger.getLogger(AcessoRemoto.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void enviarSaida(Socket alunoConectado) {
        try {
            PrintWriter printWriter = new PrintWriter(alunoConectado.getOutputStream());

        } catch (IOException ex) {
            Logger.getLogger(AcessoRemoto.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    private String converterHtmlString(BufferedReader htmlReader) {
        try {
            StringBuilder html = new StringBuilder();
            String linha = htmlReader.readLine();
            while (linha != null) {
                html.append(linha);
                linha = htmlReader.readLine();
            }
            return html.toString();

        } catch (IOException ex) {
            Logger.getLogger(AcessoRemoto.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }
    }

    private void retornarHtml1(Socket alunoConectado, String sNome) {
          try {
            System.out.println("Fui retornar html0");
            File html0 = new File("paginasResposta\\html1.xhtml");

            PrintWriter writer = new PrintWriter(alunoConectado.getOutputStream());
            BufferedReader htmlReader = new BufferedReader(new FileReader(html0));
            String htmlEmString = converterHtmlString(htmlReader);
            System.out.println(String.format(htmlEmString, sNome));
            writer.write(String.format(htmlEmString, sNome));
            writer.close();

        } catch (IOException ex) {
            Logger.getLogger(AcessoRemoto.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void retornarHtml2(Socket alunoConectado, String sNome) {
        try {
            System.out.println("Fui retornar html0");
            File html0 = new File("paginasResposta\\html2.xhtml");

            PrintWriter writer = new PrintWriter(alunoConectado.getOutputStream());
            BufferedReader htmlReader = new BufferedReader(new FileReader(html0));
            String htmlEmString = converterHtmlString(htmlReader);
            System.out.println(String.format(htmlEmString, sNome));
            writer.write(String.format(htmlEmString, sNome));
            writer.close();

        } catch (IOException ex) {
            Logger.getLogger(AcessoRemoto.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void retornarHtml3(Socket alunoConectado, String sNome) {
        try {
            System.out.println("Fui retornar html3");
            File html0 = new File("paginasResposta\\html3.xhtml");

            PrintWriter writer = new PrintWriter(alunoConectado.getOutputStream());
            BufferedReader htmlReader = new BufferedReader(new FileReader(html0));
            String htmlEmString = converterHtmlString(htmlReader);
            System.out.println(String.format(htmlEmString, sNome, sNome, sNome, sNome));
            writer.write(String.format(htmlEmString, sNome, sNome, sNome, sNome));
            writer.close();

        } catch (IOException ex) {
            Logger.getLogger(AcessoRemoto.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    private void retornarHtml4(Socket alunoConectado, String sNome){
         try {
            System.out.println("Fui retornar pagina 4");
            File html0 = new File("paginasResposta\\html4.xhtml");
            
            PrintWriter writer = new PrintWriter(alunoConectado.getOutputStream());
            BufferedReader htmlReader = new BufferedReader(new FileReader(html0));
            String htmlEmString = converterHtmlString(htmlReader);
            System.out.println(String.format(htmlEmString, sNome));
            writer.write(String.format(htmlEmString, sNome));
            writer.close();

        } catch (IOException ex) {
            Logger.getLogger(AcessoRemoto.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void retornarHtml5(Socket alunoConectado) {
        try {
            System.out.println("Fui retornar pagina 5");
            File html0 = new File("paginasResposta\\html5.xhtml");
            
            PrintWriter writer = new PrintWriter(alunoConectado.getOutputStream());
            BufferedReader htmlReader = new BufferedReader(new FileReader(html0));
            String htmlEmString = converterHtmlString(htmlReader);
            writer.write(htmlEmString);
            writer.close();

        } catch (IOException ex) {
            Logger.getLogger(AcessoRemoto.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
